<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="项目名称" size="small">
            <el-input v-model="searchForm.tenderName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="datePicker">
          <el-form-item label="时间区间" size="small">
            <el-date-picker type="date" placeholder="选择开始日期" value-format="yyyy-MM-dd" v-model="searchForm.startTimeStr"
            ></el-date-picker>
            <span>-</span>
            <el-date-picker type="date" placeholder="选择结束日期" value-format="yyyy-MM-dd" v-model="searchForm.endTimeStr"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="所属团队" size="small">
            <el-input v-model="searchForm.teamName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="备注说明" size="small">
            <el-input v-model="searchForm.remark"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <!--<el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>-->
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="440px">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="80px">
          <el-form-item label="有无项目" size="small">
            <el-switch
              v-model="teamRow.isExist"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value=1
              :inactive-value=0
            >
            </el-switch>
          </el-form-item>
          <el-form-item prop="tenderName" v-if="teamRow.isExist" label="投标项目" size="small">
            <el-autocomplete
              v-model="teamRow.tenderName"
              :fetch-suggestions="querySearchProject"
              @select="handleSelectProject"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item v-if="teamRow.teamName && teamRow.isExist" label="所属团队" size="small">
            {{teamRow.teamName}}
          </el-form-item>
          <el-form-item v-if="teamRow.partyA && teamRow.isExist" label="招标方" size="small">
            {{teamRow.partyA}}
          </el-form-item>
          <div v-if="!teamRow.isExist">
            <el-form-item prop="teamName" label="所属团队" size="small">
              <el-autocomplete
                v-model="teamRow.teamName"
                :fetch-suggestions="querySearchTeam"
                @select="handleSelectTeam"
                placeholder="请输入内容"
              >
              </el-autocomplete>
            </el-form-item>
          </div>

          <el-form-item prop="billAmount" label="收款金额" size="small">
            <el-input type="number" v-model.number="teamRow.billAmount">
              <span slot="suffix">万元</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="billTime" label="收款时间" size="small">
            <el-date-picker
              v-model="teamRow.billTime"
              type="date"
              value-format="timestamp"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="银行名称" size="small">
            {{teamRow.bankName}}
          </el-form-item>
          <el-form-item prop="receivingUnit" label="收款单位" size="small">
            <el-select v-model="teamRow.receivingUnit" placeholder="请选择" @change="receivingUnitChange">
              <el-option
                v-for="item in global.billUnitList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注说明" size="small">
            <el-input type="textarea" v-model="teamRow.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
          <el-button size="small" @click="outerVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <el-dialog title="补偿金支出" :visible.sync="outerBillVisible" width="440px">
        <el-form ref="billRow" :rules="billRules" :model="billRow" label-width="110px">
          <el-form-item v-if="billRow.tenderName" label="投标项目" size="small">
            {{billRow.tenderName}}
          </el-form-item>
          <el-form-item v-if="billRow.teamName" label="所属团队" size="small">
            {{billRow.teamName}}
          </el-form-item>
          <el-form-item v-if="billRow.partyA" label="招标方" size="small">
            {{billRow.partyA}}
          </el-form-item>
          <el-form-item prop="costAmount" label="支出金额" size="small">
            <el-input type="number" v-model.number="billRow.costAmount">
              <span slot="suffix">万元</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="costTime" label="支出时间" size="small">
            <el-date-picker
              v-model="billRow.costTime"
              type="date"
              value-format="timestamp"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="payer" label="收款人" size="small">
            <el-autocomplete
              v-model="billRow.payer"
              :fetch-suggestions="querySearchOperator"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small" @click="submitBillForm('billRow')">确定</el-button>
          <el-button size="small" @click="outerBillVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
      :show-summary="true"
    >
      <el-table-column
        slot="opt"
        label="操作"
        fixed="right"
        width="80">
        <template slot-scope="scope">
          <!--<el-button-->
            <!--@click.native.prevent="editBill(scope.row.billId,0)"-->
            <!--type="text"-->
            <!--size="small">-->
            <!--补偿金支出-->
          <!--</el-button>-->
          <el-button
            @click.native.prevent="editTeam(scope.row.billId,1)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import {
    addTenderCompensation,
    deleteTenderCompensation,
    getTenderCompensationList,
    selectProjectName,
    selectTeam,
    selectTenderCompensation,
    updateTenderCompensation,
    selectOperator,
    updateCost
  } from '@/api/tendercompensation'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const time = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const isExist = function(row, column) {
    return row.isExist ? '有' : '无'
  }

  const receivingUnit = function(row, column) {
    if (row.receivingUnit) {
      let obj = {}
      obj = global.billUnitList.find((item) => {
        return item.value === row.receivingUnit // 筛选出匹配数据
      })
      return obj.label
    }
  }
  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      const validateCostAmount = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入支出金额!'))
        } else if (value > this.billRow.balance) {
          callback(new Error('请输入正确金额!'))
        } else {
          callback()
        }
      }
      const validateBillAmount = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入收款金额!'))
        } else if (value < this.billAmount - this.teamRow.balance) {
          callback(new Error('收款金额须大于支出金额!'))
        } else {
          callback()
        }
      }
      return {
        colConfigs: [
          { prop: 'isExist', label: '有无项目', width: '80', fixed: true, formatter: isExist },
          { prop: 'tenderName', label: '投标项目名称', minWidth: '35%', fixed: true },
          { prop: 'teamName', label: '团队名称', width: '100' },
          { prop: 'balance', label: '剩余余额(万元)', width: '100' },
          { prop: 'billAmount', label: '收款金额(万元)', width: '100' },
          { prop: 'partyA', label: '招标方', minWidth: '20%' },
          { prop: 'billTime', label: '收款时间', width: '100', component: time },
          { prop: 'bankName', label: '银行名称', width: '150' },
          { prop: 'receivingUnit', label: '收款单位', width: '100', formatter: receivingUnit },
          { prop: 'remark', label: '备注说明', minWidth: '20%' },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        costTypes: [],
        typeNames: [],
        listLoading: true,
        dialogTitle: '新增投标补偿金',
        marginTitle: '',
        marginType: 1,
        dialogType: 0,
        teamRow: {},
        teamRowClear: {},
        billRow: {},
        margin: {},
        marginClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        outerBillVisible: false,
        pca: pca,
        rules: {
          tenderName: [
            { required: true, message: '请输入项目名称', trigger: 'change' }
          ],
          teamName: [
            { required: true, message: '请输入团队名称', trigger: 'change' }
          ],
          partyA: [
            { required: true, message: '请输入招标方', trigger: 'change' }
          ],
          billTime: [
            { required: true, message: '请选择收款时间', trigger: 'change' }
          ],
          billAmount: [
            { required: true, trigger: 'change', validator: validateBillAmount }
          ],
          receivingUnit: [
            { required: true, message: '请选择收款单位', trigger: 'change' }
          ]
        },
        billRules: {
          costTime: [
            { required: true, message: '请选择支出时间', trigger: 'change' }
          ],
          costAmount: [
            { required: true, trigger: 'change', validator: validateCostAmount }
          ],
          payer: [
            { required: true, message: '请输入收款人', trigger: 'change' }
          ]
        },
        visible: false,
        visibleType: 0,
        billAmount: 0
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    computed: {
      global() {
        return global
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.searchFormList.billType = 1
        this.listLoading = true
        getTenderCompensationList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          console.log(this.tableData)
          this.listLoading = false
        })
      },
      provinceChange() {
        this.searchForm.cityId = ''
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '新增投标补偿金'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
      },
      editTeam(billId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改投标补偿金'
        this.dialogType = 0
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          billId: billId
        }
        selectTenderCompensation(params).then(response => {
          this.teamRow = response.responseBody
          this.teamRow.tenderId = this.teamRow.projectId
          this.billAmount = this.teamRow.billAmount
        })
      },
      editBill(billId) {
        if (this.$refs['billRow']) {
          this.$refs['billRow'].resetFields()
        }
        this.outerBillVisible = true
        const params = {
          billId: billId
        }
        selectTenderCompensation(params).then(response => {
          this.billRow = response.responseBody
          delete this.billRow.costAmount
          delete this.billRow.costTime
          delete this.billRow.payer
        })
      },
      submitForm(formName) {
        const params = {
          isExist: this.teamRow.isExist,
          teamId: this.teamRow.teamId,
          teamName: this.teamRow.teamName,
          partyA: this.teamRow.partyA,
          billAmount: this.teamRow.billAmount,
          billTime: this.teamRow.billTime,
          receivingUnit: this.teamRow.receivingUnit,
          receivingUnitName: this.teamRow.receivingUnitName,
          remark: this.teamRow.remark ? this.teamRow.remark : ''
        }
        if (this.teamRow.isExist) {
          params.projectId = this.teamRow.tenderId
          params.tenderName = this.teamRow.tenderName
          if (!this.teamRow.tenderId) {
            this.$message({
              message: '该项目不存在',
              type: 'warning'
            })
            return
          }
        }
        if (!this.dialogType) {
          params.billId = this.teamRow.billId
          params.dateCreated = this.teamRow.dateCreated
        }
        if (this.teamRow.teamId) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.dialogType) {
                addTenderCompensation(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.fetchData()
                })
              } else {
                updateTenderCompensation(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.fetchData()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          this.$message({
            message: '该团队不存在',
            type: 'warning'
          })
        }
      },
      submitBillForm(formName) {
        const params = {
          isTender: 1,
          billId: this.billRow.billId,
          projectId: this.billRow.projectId,
          teamId: this.billRow.teamId,
          partyA: this.billRow.partyA,
          costAmount: this.billRow.costAmount,
          costTime: this.billRow.costTime,
          payer: this.billRow.payer,
          balance: this.billRow.balance
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            updateCost(params).then(response => {
              console.log(response)
              this.outerBillVisible = false
              this.fetchData()
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          billId: scope.row.billId,
          teamId: scope.row.teamId,
          dateCreated: scope.row.dateCreated,
          billAmount: scope.row.billAmount,
          isDel: 1
        }
        deleteTenderCompensation(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      receivingUnitChange(event) {
        let obj = {}
        obj = this.global.billUnitList.find(function(item) {
          return item.value === event
        })
        this.$set(this.teamRow, 'receivingUnitName', obj.label)
      },
      querySearchTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.teamId
        if (queryString) {
          const params = {
            teamName: queryString
          }
          selectTeam(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.teamName
            }
            let teamList = response.responseBody
            if (teamList.length === 0) {
              teamList = [{ value: '暂无数据' }]
            }
            callback(teamList)
          })
        } else {
          callback([])
        }
      },
      handleSelectTeam(item) {
        this.$set(this.teamRow, 'teamId', item.teamId)
      },
      querySearchProject(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.tenderId
        if (queryString) {
          const params = {
            tenderName: queryString
          }
          selectProjectName(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.tenderName
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectProject(item) {
        this.$set(this.teamRow, 'tenderId', item.tenderId)
        this.$set(this.teamRow, 'tenderName', item.tenderName)
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
        this.$set(this.teamRow, 'partyA', item.partyA)
      },
      querySearchOperator(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            name: queryString,
            teamId: this.billRow.teamId
          }
          selectOperator(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.name
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      }
    },
    mounted() {
      console.log(this.pca)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
